package com.uzai.console.service.tb.tbtokennew.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.tb.tbtokennew.TbTokenNewCallBackDto;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.TbRidToken;
import com.uzai.console.entity.TbTokenNew;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.TbRidTokenMapper;
import com.uzai.console.mapper.TbTokenNewMapper;
import com.uzai.console.service.tb.tbridpid.TbRidPidService;
import com.uzai.console.service.tb.tbtokennew.TbTokenNewCallBackService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月31日 20:10
 */
@Service
public class TbTokenNewCallBackServiceImpl implements TbTokenNewCallBackService {

    private Logger logger = LoggerFactory.getLogger(TbTokenNewCallBackServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private TbTokenNewMapper tbTokenNewMapper;
    @Autowired
    private TbRidTokenMapper tbRidTokenMapper;
    @Autowired
    private TbRidPidService tbRidPidService;

    @Transactional
    @Override
    public void add(TbTokenNew tbTokenNew) {
        Merchant merchant = merchantMapper.selectById(tbTokenNew.getMerId());
        if (merchant==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有该运营商");
        }
        TbTokenNew at = tbTokenNewMapper.selectByUserId(tbTokenNew.getUserId());
        //该淘宝联盟账号不存在，则新增加
        if (at == null){
            tbTokenNewMapper.insertSelective(tbTokenNew);
        }else{
            if(at.getType().intValue() != tbTokenNew.getType().intValue()){//验证type是否一样，不一样即淘宝和饿了么共有
                tbTokenNew.setType(2); //2-淘宝和饿了么共有
            }
            logger.info(at.getMerId() + "::" + tbTokenNew.getMerId());
            if (at.getMerId().longValue() != tbTokenNew.getMerId().longValue()){
                Merchant merchant1 = merchantMapper.selectById(at.getMerId());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.ALIMM_ACCOUNT_EXIST, CommonUtil.mobileFormat(merchant1.getMobile())));
            }
            tbTokenNew.setId(at.getId());
            tbTokenNew.setVersion(at.getVersion());
            int count = tbTokenNewMapper.updateSelective(tbTokenNew);
            if (count != 1){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
            }
        }
    }

    //处理买家身份的饿了么联盟
    private void addTbRidToken(TbRidToken tbRidToken) {
        TbRidToken at = tbRidTokenMapper.selectByUserId(tbRidToken.getUserId());
        //该淘宝联盟账号不存在，则新增加
        if (at == null){
            tbRidTokenMapper.insertSelective(tbRidToken);
        }else{ //存在修改
            tbRidToken.setId(at.getId());
            tbRidTokenMapper.updateById(tbRidToken);
        }
    }

    @Transactional
    @Override
    public void oauth(TbTokenNewCallBackDto tbTokenNewCallBackDto){

        if(StringUtils.isBlank(tbTokenNewCallBackDto.getTokenInfo())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "授权信息不能为空");
        }
        Map<String,Object> tokenVo = JSONObject.parseObject(tbTokenNewCallBackDto.getTokenInfo(), Map.class);
        if (tokenVo.get("error") != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, tokenVo.get("error").toString());
        }

        String state = tbTokenNewCallBackDto.getState();
        if(StringUtils.isBlank(state)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "自定义参数不能为空");
        }

        if(StringUtils.isBlank(tbTokenNewCallBackDto.getTokenInfo())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "token数据不能为空");
        }

        try{

            //获取系统版本
            String version = state.substring(0,2);
            //去掉前面2位版本号，为merId_type拼凑的参数
            state = state.substring(2);

            //新建token
            int now = DateUtil.getNowTime();
            TbTokenNew tbTokenNew = new TbTokenNew();
            tbTokenNew.setUserName(URLDecoder.decode(tokenVo.get("taobao_user_nick").toString(),"UTF-8"));
            tbTokenNew.setUserId(Long.valueOf(tokenVo.get("taobao_user_id").toString()));
            tbTokenNew.setAccessToken(tokenVo.get("access_token").toString());
            tbTokenNew.setRefreshToken(tokenVo.get("refresh_token").toString());
            tbTokenNew.setExpiresin(Integer.parseInt(tokenVo.get("expires_in").toString()));
            tbTokenNew.setReExpiresin(Integer.parseInt(tokenVo.get("re_expires_in").toString()));
            tbTokenNew.setAuthTime(now);
            tbTokenNew.setCreateTime(now);
            tbTokenNew.setUpdateTime(now);
            tbTokenNew.setExptime(now+tbTokenNew.getExpiresin());

            //3.0系统调用授权
            if("v3".equals(version)){
                //state 为merId_type拼凑的参数
                String[] stateArr = state.split("_");
                if(stateArr == null || stateArr.length != 2){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "自定义参数格式不正确");
                }

                if(Integer.parseInt(stateArr[1]) == 2){ //买家身份的饿了么授权
//                    TbRidToken tbRidToken = new TbRidToken();
//                    tbRidToken.setId(IdWorker.getId());
//                    tbRidToken.setAccessToken(tbTokenNew.getAccessToken());
//                    tbRidToken.setUserId(String.valueOf(tbTokenNew.getUserId()));
//                    tbRidToken.setExptime(tbTokenNew.getExptime());
//                    tbRidToken.setCreateTime(tbTokenNew.getCreateTime());
//                    tbRidToken.setUpdateTime(tbTokenNew.getUpdateTime());
//                    addTbRidToken(tbRidToken);

                }else{ //正常的淘宝或者饿了么联盟
                    tbTokenNew.setId(IdWorker.getId());
                    //merId
                    tbTokenNew.setMerId(Long.parseLong(stateArr[0]));
                    //类型
                    tbTokenNew.setType(Integer.parseInt(stateArr[1]));
                    //调用token保存方法
                    add(tbTokenNew);
                }
            }else { //2.0系统调用授权，则刷新授权
                TbTokenNew tbTokenNew_old = tbTokenNewMapper.selectByUserId(tbTokenNew.getUserId());
                if(tbTokenNew_old != null){//刷新授权
                    tbTokenNew_old.setUserName(URLDecoder.decode(tokenVo.get("taobao_user_nick").toString(),"UTF-8"));
                    tbTokenNew_old.setAccessToken(tokenVo.get("access_token").toString());
                    tbTokenNew_old.setRefreshToken(tokenVo.get("refresh_token").toString());
                    tbTokenNew_old.setExpiresin(Integer.parseInt(tokenVo.get("expires_in").toString()));
                    tbTokenNew_old.setReExpiresin(Integer.parseInt(tokenVo.get("re_expires_in").toString()));
                    tbTokenNew_old.setAuthTime(now);
                    tbTokenNew_old.setUpdateTime(now);
                    tbTokenNew_old.setExptime(now+tbTokenNew.getExpiresin());
                    tbTokenNewMapper.update(tbTokenNew_old);
                }
            }
        }catch(Exception e){
            logger.error("----解析淘宝联盟token错误---error={}", e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
        }
    }

}
